#from datetime import datetime
from os import path,makedirs,listdir,walk
from zipfile import ZipFile
import requests
from time import localtime, strftime
from flask import send_file
from database import OperateDatabase
from init_excel import create_excel, get_sheet, write_excel
from re import match, search

t=localtime()
now_date=strftime("%y%m%d",t)
# current_time = datetime.now()  #获取当前时间
# #print(current_time)
# print('今天是{}年{}月{}日{}点{}分{}秒'.format(current_time.year,current_time.month,current_time.day,current_time.hour,current_time.minute,current_time.second))

save_path_dir=f'static/images/{now_date}/'#f'static/images/{current_time.year}-{current_time.month}-{current_time.day}/'

def create_dir(save_dir=save_path_dir):
    if not path.exists(save_dir):
        print('不存在文件夹')
        makedirs(save_dir)

# def find_max_num():
#     save_dir = f'static/images/{get_date()}/'
#     create_dir(save_dir)
#     files = listdir(save_dir)
#     max=0
#     for file in files:
#         num=float(file.replace('.png',''))#int(file.split('(')[1].split(')')[0])
#         if num>max:
#             max = num
#         print(max)
#     return max

def find_max_num():
    save_dir = f'static/images/{get_date()}/'
    create_dir(save_dir)

    # 遍历所有文件名
    result = []
    for filename in listdir(save_dir):
        # 匹配文件名中的数字部分，包括小数
        n = match(r'^\d+\.*\d*', filename)
        if n:
            # 如果匹配到数字，则将结果转换为float类型
            num = float(n.group())
            # 筛选掉小数点后不是“.png”的文件名
            if filename[len(n.group()):].startswith('.png'):
                result.append(num)
    # 取结果列表最大值
    if result:
        return max(result)
    return 0

def find_max_nums():
    save_dir = f'static/images/{get_date()}/'
    create_dir(save_dir)

    # 遍历所有文件名并提取数字
    nums = []
    for filename in listdir(save_dir):
        # 匹配文件名中的数字部分，包括小数
        n = match(r'^\d+\.*\d*', filename)
        if n:
            # 如果匹配到数字，则将结果转换为float类型
            num = float(n.group())
            # 筛选掉小数点后不是“.png”的文件名
            if filename[len(n.group()):].startswith('.png'):
                nums.append(num)

    # 对结果从大到小排序
    nums.sort(reverse=True)

    # 取前六个数字，不足六个的用0补齐
    max_nums = nums[:6] + [0] * (6 - len(nums))

    return max_nums

def get_time():
    time_str=strftime('%Y{}%m{}%d %X')#{}
    return time_str.format('-','-')#'年','月','日'
    #return str(current_time).split('.')[0]

def get_date():
    t = localtime()  # 格式化格式
    date = strftime("%y%m%d", t)
    return date

def find_time(text):
    return search(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}', text).group()

def post_file(filename,mode='test.py'):
    #token = get_token()

    if mode=='remote':
        post_file_url = 'h7153156i4.zicp.fun:36117/command'#https://h7153156i4.zicp.fun/command
    elif mode=='test.py':
        post_file_url = 'http://127.0.0.1:8888/command'#s
    else:
        post_file_url = 'http://192.168.199.213:8888/command'
    # headers = {
    #     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'
    #     , 'Accept-Language': 'zh-CN,zh;q=0.9', 'Accept-Encoding': 'gzip, deflate'}#, 'token': 'token'

    send_flag=False

    files = {"file": open(filename, 'rb'), "Content-Type": "text/html; charset=utf-8",
              "filename": filename}#"Content-Disposition": "form-data",
    try:
      requests.post(url=post_file_url, files=files, verify=True)#, headers=headers verify=False
      print('上传成功')
      send_flag=True
    except Exception as e:
         print('连接失败')
         print(e)

    return send_flag

# def get_img_info(img):
#     with open(img, 'rb') as f:
#         tags = process_file(f)
#         print(tags)
#         #date = datetime.strptime(str(tags['EXIF DateTimeOriginal']), '%Y:%m:%d %H:%M:%S')
#         #print('Image DateTime', tags['Image DateTime'])
#         # print('拍摄时间：', date)
#         # return date

def init_database():
    setting = {
        'host': 'mysql.sqlpub.com',  # 10.0.24.5 localhost
        'user': 'teamonitor',  #root
        'password': '0249a15c3d72f4aa',  # 1234
        'port': 3306,
        'charset': 'utf8mb4',
        'database': '',  # 默认是None或''，可以对所有数据库操作
        'autocommit': True  # 提交，插入、删除和更新数据库才会生效
    }

    db = OperateDatabase(setting)
    db.use_database('teamonitor')

    return db

def generate_data():
    from random import random, uniform
    ds = get_time()  # '2022-10-23 00:00:00'
    moisture_content = format(random(), '.3f')
    tender_bud_rate = format(random(), '.3f')
    air_temperature = format(uniform(10, 34), '.1f')
    air_humidity = format(random(), '.3f')
    data = [ds, moisture_content, tender_bud_rate, air_temperature, air_humidity]
    return data

def get_data(data):
    day, moisture_content, tender_bud_rate, air_temperature, air_humidity = [], [], [], [], []
    for a, b, c, d, e in data:  # [1:]
        day.append(a.strftime('%Y-%m-%d %X'))  #
        moisture_content.append(b)
        tender_bud_rate.append(c)
        air_temperature.append(d)
        air_humidity.append(e)
    return day, moisture_content, tender_bud_rate, air_temperature, air_humidity

def get_warn_data(data):
    days, msgs = [], []
    for day, msg in data:  # [1:]
        days.append(day.strftime('%Y-%m-%d %X'))  #
        msgs.append(msg)
    return days, msgs

def export_excel(month=None):
    db = init_database()
    if month!=None:
        data=db.get_history_month_data(month)
    else:
        data = db.get_history_data(num='all')
    day, moisture_content, tender_bud_num, air_temperature, air_humidity=get_data(data)
    db.close()
    print('已读取数据库')
    content_list=[day, moisture_content, tender_bud_num, air_temperature, air_humidity]
    if content_list!=[[], [], [], [], []]:

        #print('content_list:',content_list)
        head=['时间','含水率(%)','嫩芽数(个)','空气温度(°C)','空气湿度(%)']
        path,sheet_name=create_excel(head,excel_name='/static/茶叶数据总表.xlsx',sheet_name='')
        print('已创建表格')
        wb,sheet=get_sheet(path, sheet_name)
        print('获取sheet')
        write_excel(wb, path, sheet, content_list)
        print('已写入表格')
        return True
    else:
        print('无数据')
        return False

def export_img(month=None):
    def _(n):
        for i in range(0, 10):
            if n == i:
                n = f'0{n}'
        return str(n)

    img_source='./static/images'
    img_dirs=[]
    for dirpath, dirnames, filenames in walk(img_source):
        # for dirname in dirnames:
        #     print(path.join(dirpath, dirname))
        if dirpath!=img_source:
            if month!=None:
                t = localtime()
                year = strftime("%y", t)
                # print('路径：', dirpath)
                # print('年份：',dirpath[:2])
                # print('月份：', dirpath[2:4])
                tmppath=dirpath.split('\\')[-1]
                if (tmppath[:2]==year) and (tmppath[2:4]==_(month)):
                    print(dirpath)
                    img_dirs.append(dirpath)
            else:
                img_dirs.append(dirpath)
    return img_dirs

def export(month=None):
    data_flag = export_excel(month)
    img_dirs = export_img(month)
    if data_flag or (img_dirs != []):
        with ZipFile('茶叶数据.zip', 'w') as z:
            if data_flag:
                z.write('./static/茶叶数据总表.xlsx',arcname='茶叶数据总表.xlsx')  # ath.basename('./static/茶叶数据总表.xlsx')
            for img_dir in img_dirs:
                # print(img_dir)
                for f in listdir(img_dir):
                    # print(f)
                    z.write(img_dir + '/' + f, arcname=f)  #
        return send_file('茶叶数据.zip', as_attachment=True)  # static\images\2.jpg E:\program\PycharmProjects\web\teamonitor-master\
    else:
        if month!=None:
            return f'很遗憾，没有今年{month}月的数据！'
        else:
            return f'很遗憾，没有数据！请启动采集系统，如已启动，请耐心等待。'

if __name__ =="__main__":
    # max=find_max_num()
    # print(max)
    #post_file(r'./static/commands/stop.txt','remote')
    # img=r'E:\program\PycharmProjects\web\teamonitor-master\static\images\2023-4-13\(1).jpg'
    # # print(img)
    # # get_img_info(img)

    t=get_time()
    print(t)

    #export_excel(1)
    #print(export_img(3))
